<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="农舍名称" prop="name">
        <el-tree-select
          v-model="queryParams.farmHouseId"
          :data="deptList"
          :render-after-expand="false"
          placeholder="请选择农舍"
          @change="hangdleChange"
           style="width:240px"
        />
      </el-form-item>

      <el-form-item label="创建时间" prop="timeRange">
        <el-date-picker
          v-model="queryParams.timeRange"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>

    <div class="chart-container">
      <div ref="tempChartRef" style="height: 400px; width: 100%;" v-loading="loading" element-loading-text="努力加载中..."></div>
      <div ref="humidityChartRef" style="height: 400px; width: 100%;" v-loading="loading" element-loading-text="努力加载中..."></div>
      <div ref="co2ChartRef" style="height: 400px; width: 100%;" v-loading="loading" element-loading-text="努力加载中..."></div>
      <div ref="ventilationChartRef" style="height: 400px; width: 100%;" v-loading="loading" element-loading-text="努力加载中..."></div>
    </div>

  </ContentWrap>
</template>

<script setup lang="ts">
import { debounce } from 'lodash';
import { FarmTourApi, FarmTourVO } from '@/api/farmTour/index';
import { houseTourApi } from '@/api/houseTour/history/index';
import {farmHouseExpend} from '@/api/houseTour/houseOverview/index';
import { FarmWarnApi } from '@/api/farmTour/warn/index';
import { onMounted, ref, reactive,nextTick  } from 'vue';
import * as echarts from "echarts";

defineOptions({ name: 'History' });

const loading = ref(true);
const farmTourValue = ref<any>(null);
const farmTourList = ref<FarmTourVO[]>([]);
const houseList = ref<any[]>([]);

// 图表引用
const chartRef = ref<any>(null);
const tempChartRef = ref<any>(null);
const humidityChartRef = ref<any>(null);
const co2ChartRef = ref<any>(null);
const ventilationChartRef = ref<any>(null);
const myCharts = {
  temperature: ref<any>(null),
  humidity: ref<any>(null),
  co2: ref<any>(null),
  ventilation: ref<any>(null)
};

const deptList = ref([]); // 用于存储农舍列表
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  farmId: undefined,
  farmHouseName: undefined,
  houseId: undefined,
  farmHouseId: undefined,
  timeRange: []
});

const queryFormRef = ref();

const getHouseList = async () => {
  try {
    const res = await farmHouseExpend.getHouseListApi();
    console.log(res, 'res农舍列表');
    if (res) {
      loading.value = true;
      deptList.value = res.map(item => ({
        value: item.id,
        label: item.name,
        children: item.children ? item.children.map(child => ({
          value: child.id,
          label: child.name,
        })) : []
      }));
      // 设置默认选择，选择第一个农舍的第一个子项
      if (deptList.value.length > 0 && deptList.value[0].children.length > 0) {
        queryParams.farmHouseId = deptList.value[0].children[0].value;
        await getHistoryData(queryParams.farmHouseId);
      }
    }else{
      deptList.value = []
    }
  } catch (error) {
    console.error('请求失败:', error);
  }finally{
    loading.value = false;
  }
};

// 处理农舍选择变化
const hangdleChange = async (selectedHouseId) => {
  queryParams.farmHouseId = selectedHouseId;
  await getHistoryData(queryParams.farmHouseId);
};


const getHistoryData = async (farmHouseId:Number|undefined) => {
  const params = { 
    farmHouseId: queryParams.farmHouseId,
    createTime: queryParams.timeRange.length === 2 ? queryParams.timeRange : undefined
  };
  try {
    loading.value = true;
    const res = await houseTourApi.getHouseHistory(params);
    console.log(res, 'res图表');
    const timeData: string[] = [];
    const innerTempData: number[] = [];
    const outerTempData: number[] = [];
    const humidityData: number[] = [];
    const co2Data: number[] = [];
    const ventilationData: number[] = [];

    res.forEach((data: { 
      createTime: number; 
      innerTemp: number; 
      outerTemp: number; 
      innerHumi: number; 
      innerCo2: number; 
      innerPres: number 
    }) => {
      timeData.push(new Date(data.createTime).toLocaleString());
      innerTempData.push(data.innerTemp);
      outerTempData.push(data.outerTemp);
      humidityData.push(data.innerHumi);
      co2Data.push(data.innerCo2);
      ventilationData.push(data.innerPres);
    });

     await nextTick(); // 确保 DOM 更新
      drawChart(tempChartRef.value, '温度(℃)', ['内部温度', '外部温度'], [innerTempData, outerTempData], timeData);
      drawChart(humidityChartRef.value, '湿度(%)', ['湿度'], [humidityData], timeData);
      drawChart(co2ChartRef.value, '二氧化碳(ppm)', ['二氧化碳浓度'], [co2Data], timeData);
      drawChart(ventilationChartRef.value, '室内压强(Pa)', ['室内压强'], [ventilationData], timeData);
  } catch (error) {
    console.error('请求数据时出错:', error);
  } finally {
    loading.value = false;
  }
};

const drawChart = (chartRef, title, legendData, seriesDataList, xAxisData) => {
  // 绘制图表
  if (!chartRef) {
    console.error('chartRef is not available');
    return;
  }
  try {
    const myChart = echarts.init(chartRef);
    const series = legendData.map((name, index) => ({
      name,
      type: 'line',
      smooth: true,
      data: seriesDataList[index] || [],
      symbolSize: 1,
    }));

    const options = {
      title: { text: title },
      tooltip: { trigger: 'axis' },
      legend: { data: legendData },
      toolbox: {
        show: true,
        feature: {
          magicType: { type: ['line', 'bar', 'pie'] },
          restore: {},
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xAxisData || [],
      },
      yAxis: { type: 'value' },
      series: series,
      dataZoom: [
        { type: 'slider', start: 0, end: 100 },
        { type: 'inside' }
      ],
      markPoint: {
        data: [{ type: 'max', name: '最大值' }],
      }
    };

    myChart.setOption(options);
    window.addEventListener('resize', () => { myChart.resize(); });
  } catch (error) {
    console.error('绘制图表时出错:', error);
  }
};
const handleQuery = async () => {
  await getHistoryData(queryParams.farmHouseId); 
};

const resetQuery = () => {
  queryParams.timeRange = []; // 重置时间范围
  queryFormRef.value.resetFields();
  handleQuery(); 
};

const debouncedGetHouseList = debounce(async (newValue) => {

}, 300);

onMounted(() => {
  getHouseList();
});
</script>

<style scoped>
h1 {
  color: #333;
}
.chart-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr); 
  gap: 20px 20px;
  margin: 20px 0;
}
</style>
